import {
	get,
	post
} from '../../utils/request.js'
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		userName: '',
		phone: '',
		detailAdd: '',
		checked: false,
		region: [],
		customItem: '全部',
		address: '',
		id: '',
		res: ''
	},
	onLoad(options) {
		// console.log(options)
		if ( options.id ) {
			this.setData({
				id: options.id,
			})
		}
		if (options.res) {
			this.setData({
				res: JSON.parse(decodeURIComponent(options.res))
			})
		}
		if (this.data.res) {
			// console.log(this.data.res)
			this.setData({
				userName: this.data.res.userName,
				phone: this.data.res.telNumber,
				address: `${this.data.res.provinceName} ${this.data.res.cityName} ${this.data.res.countyName}`,
				detailAdd: this.data.res.detailInfo,
			})
		}
		if (this.data.id) {
			this.getDetail()
		}
	},
	inputName(e) {
		// console.log(e)
		let value = e.detail.value
		this.setData({
			userName: value
		})
	},
	inputPhone(e) {
		let value = e.detail.value
		this.setData({
			phone: value
		})
	},
	inputDetailAdd(e) {
		let value = e.detail.value
		this.setData({
			detailAdd: value
		})
	},
	checkedChange(e) {
		// console.log(e.detail.value[0])
		this.setData({
			checked: e.detail.value[0]
		})
	},
	regionChange(e) {
		// console.log(e)
		let value = e.detail.value
		let address = `${value[0]} ${value[1]} ${value[2]}`
		// console.log(address)
		this.setData({
			address: address
		})
	},
	addWXAddress() {
		wx.chooseAddress({
			success: res => {
				// console.log(res)
				this.setData({
					userName: res.userName,
					phone: res.telNumber,
					address: `${res.provinceName} ${res.cityName} ${res.countyName}`,
					detailAdd: res.detailInfo
				})
			}
		})
	},
	async saveAddress() {
		if (!this.data.userName || !this.data.phone) {
			wx.showToast({
				title: '信息未完善',
				icon: 'error',
				duration: 1000
			})
			return 
		}
		const data = await post('/address/saveAction', {
			userName: this.data.userName, // 将全部地址信息传给后端
			telNumber: this.data.phone,
			address: this.data.address,
			detailaddress: this.data.detailAdd,
			checked: this.data.checked, // 是否是默认地址
			openId: wx.getStorageSync('OPENID') || '', // 唯一身份ID
			addressId: this.data.id // 还需要出入一个地址id
		})
		if (data.data) {
			// console.log(data)
			wx.showToast({
				title: '添加成功',
				icon: 'success',
				duration: 1000,
				success: res=> {
					wx.navigateTo({
						url: '/pages/address/address'
					})
				}
			})
		}
	},
	async getDetail () {
		const data = await get('/address/detailAction', {
			id: this.data.id
		})
		let detail = data.data
		this.setData({
			userName: detail.name,
			phone: detail.mobile,
			address: detail.address,
			detailAdd: detail.address_detail,
			checked: detail.is_default == 1 ? true : false
		})
	}
})
